import { baseServerUrl } from '../global/server'
import axios from 'axios'
import store from '../store'
import globalMessage from '@/components/common/message/m-message'
import { getToken } from '@/global/storage'
import globalEnum, { enumToJson } from '@/global/enum'
import config from '@/config'
const myEnum = {
  ResponseCode: globalEnum.RESPONSE_CODE
}

const axiosInstance = axios.create({
  baseURL: baseServerUrl,
  timeout: config.timeout,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  withCredentials: true //当请求为跨域类型时，是否在请求中携带 cookie 信息，默认值是 false
})

// request interceptor
axiosInstance.interceptors.request.use(
  (config) => {
    // before request
    let { tokenName, tokenValue } = getToken() || {}
    tokenName && (config.headers[tokenName] = tokenValue)
    axiosUtil[config.method](config)
    return config
  },
  (error) => {
    errorHandle(error)
  }
)
// response interceptor
axiosInstance.interceptors.response.use(
  (response) => {
    let res
    if (response.data === undefined) {
      // IE9时response.data是undefined，因此需要使用response.request.responseText(Stringify后的字符串)
      res = JSON.parse(response.request.responseText)
    } else {
      res = response.data
    }
    if (res.code === myEnum.ResponseCode.noAuth) {
      store.dispatch('user/logout')
      return errorHandle(res)
    } else if (response.config.responseType === 'blob') {
      return response
    } else if (
      res.code === myEnum.ResponseCode.success ||
      res.code === myEnum.ResponseCode.failure ||
      res.code === myEnum.ResponseCode.handle
    ) {
      return res
    } else {
      return errorHandle(res)
    }
  },
  (err) => {
    let message = err.message
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          message = requestMsg.reqError
          break
        case 401:
          message = requestMsg.noAuth
          break
        case 403:
          message = requestMsg.reject
          break
        case 404:
          message = `${requestMsg.errorUrl}${err.response.config.url}`
          break
        case 408:
          message = requestMsg.timeout
          break
        case 500:
          message = requestMsg.serverError
          break
        case 502:
          message = requestMsg.netGateError
          break
        case 503:
          message = requestMsg.invalidServer
          break
        case 504:
          message = requestMsg.netGateTimeout
          break
        case 505:
          message = requestMsg.versionError
          break
        default:
      }
    }
    return errorHandle(err)
  }
)

const axiosUtil = {
  GET: 'get',
  POST: 'post',
  PUT: 'put',
  DELETE: 'delete',
  CONTENTTYPE_JSON: 'application/json;charset=utf-8',
  CONTENTTYPE_FORM: 'application/x-www-form-urlencoded',
  CONTENTTYPE_FILE: 'multipart/form-data',

  get() {},
  put(config) {},
  delete() {},
  post(config) {
    if (config.data instanceof FormData) {
      return
    }
    const contentType = config.headers['Content-Type']
    contentType && (config.data = getData(config.data, contentType))
    return config
  }
}

const getData = function (data, contentType) {
  if (contentType.indexOf(axiosUtil.CONTENTTYPE_FORM) !== -1) {
    // transfer the data to formData
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret.substring(0, ret.length - 1)
  } else if (contentType.indexOf(axiosUtil.CONTENTTYPE_FILE) !== -1) {
    let formData = new FormData()
    Object.keys(data).forEach((key) => {
      formData.append(key, data[key])
    })
    return formData
  } else {
    return data
  }
}
const errorHandle = function (err) {
  store.dispatch('setting/setPageLoading', false)
  globalMessage({
    type: 'error',
    message: err.message
  })
  return Promise.reject(err)
}

const requestMsg = {
  success: '成功',
  failure: '失败',
  error: '异常',
  loading: '请求中，请稍后。。。',
  wrongParams: '参数有误',
  expire: '身份过期，请重新登录',
  reqError: '请求错误',
  noAuth: '未授权',
  reject: '拒绝访问',
  errorUrl: '请求地址出错：',
  timeout: '请求超时',
  serverError: '服务器内部错误',
  netGateError: '网关错误',
  invalidServer: '服务不可用',
  netGateTimeout: '网关超时',
  versionError: 'HTTP版本不受支持'
}

export default axiosInstance
